package bidgetserver;

import java.io.IOException;
//import java.util.Date;
import java.util.Date;
import java.util.List;
//import java.util.List;
//import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import emailModule.emailSender;
//import com.google.appengine.api.users.User;
//import com.google.appengine.api.users.UserService;
//import com.google.appengine.api.users.UserServiceFactory;

import SmsModule.SmsSender;
import bidgetserver.Product;
import bidgetserver.PMF;

public class UpdatePrice extends HttpServlet {
    //private static final Logger log = Logger.getLogger(SignGuestbookServlet.class.getName());

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
       
        String userName = req.getParameter("userName");
        String priceID = req.getParameter("ID");
        String timeID = req.getParameter("timeID");
        String price = req.getParameter("price");
        String timeToAlert= req.getParameter("timeToAlert");
        
		String BidGetLogoPicStr="<img src='http://img199.imageshack.us/img199/5971/bidgetlogo3.png'>";
		String ContactUsStr="Contact us at:<br><B>auction.notifier@gmail.com</B>";

        PersistenceManager pm = PMF.get().getPersistenceManager();
        if(priceID != null){
        
        	String query = "select from "+Product.class.getName()+" where author == '"+userName+"'";
        	query += " && ProductKey == '"+priceID+"' && flag == true";
        	
        	List<Product> user = (List<Product>) pm.newQuery(query).execute();
        	
        	if(!user.isEmpty()){
        		Product P = user.get(0);
        		String oldUserBid=user.get(0).getPrice();
        		String productPicStr=user.get(0).getProductPicture();
        		String ProductNameStr = user.get(0).getProductName();
        		Product newUser = new Product(userName, P.getKey(), P.BuyOrSell(), P.getDate(), P.getflag(),P.getProductPicture(), P.getProductName(), P.getCellNum());
        		newUser.setPrice(price);
        		pm.deletePersistent(P);
        		pm.makePersistent(newUser);
        		
        		if(!oldUserBid.equals("100000000")){
            		//mail sending to client:
            		String MsgBodyString = "Dear <B>" +userName+"</B>,"+"<br><br>";
            		MsgBodyString+="Your bid of <B>"+oldUserBid+"$</B> on <B>"+ProductNameStr+"</B> was just out bid.<br>";
            		MsgBodyString+="eBay auction ID: <B>"+priceID+".</B><br>";
            		MsgBodyString+="please check out your Bidget bidding widget (or eBay) for recent changes."+"<br><br>";
            		MsgBodyString+="Thank you,"+"<br>";
            		MsgBodyString+="Bidget Team.";
            		
            		//if a picture was supplied for the product. put it in the mail:
            		if(!(productPicStr.equals(null)) && !(productPicStr.equals(""))){
            			MsgBodyString+="<br><br><B>Product picture bellow:</B><br>";
            			String imgStr = "<img src='"+productPicStr+"' align='middle'><br><br>"; 
            			MsgBodyString+=imgStr;
            			
            		}
            		
            		MsgBodyString+="<table><tr></tr><td>____________________________________________________________</td><tr><td>"+BidGetLogoPicStr+"</td></tr><tr><td>";
            		MsgBodyString+=ContactUsStr;
            		MsgBodyString+="</td></tr></table>";
            		
            		emailSender.SendEmail(userName, 
            				"You were just outbid! - BidGet automatic notification", MsgBodyString);
            	}
        	}

        }
        if(timeID != null){
        	String query2 = "select from "+Product.class.getName()+" where author == '"+userName+"'";
        	query2 += " && ProductKey == '"+timeID+"' && flag == true";
        	
        	List<Product> user2 = (List<Product>) pm.newQuery(query2).execute();
        	if(!user2.isEmpty()){
        		Product P2 = user2.get(0);
        		String userBid =user2.get(0).getPrice();
        		String productPicStr2 = user2.get(0).getProductPicture();
        		String  ProductNameStr2 = user2.get(0).getProductName();
        		
        		String CellNumStr = user2.get(0).getCellNum();
        		
        		Product newUser2 = new Product(userName, timeID, P2.BuyOrSell(), P2.getDate(), P2.getflag(),P2.getProductPicture(), P2.getProductName(), P2.getCellNum());
        		newUser2.setAlert();
        		//Product(String author, String content, String IsBuy, Date date, boolean flag)
        		pm.deletePersistent(P2);
        		pm.makePersistent(newUser2);
        		//call the function to alert the product ID = timeID is closing to an end
        		
        		//mail sending to client:
        		String MsgBodyString2 = "Dear <B>" +userName+"</B>,"+"<br><br>";
        		MsgBodyString2+="<font color='red'>Your bid on <B>"+ProductNameStr2+"</B> is about to end in "+timeToAlert+" minutes!</font><br>";
        		MsgBodyString2+="eBay auction ID: <B>"+timeID+"</B>.<br><br>";     		
        		
        		if( userBid.equals("100000000")){
        			MsgBodyString2+="You're not the lead bidder for this item!<br>";
        		    MsgBodyString2+="you can try bidding more before the auction ends.<br><br>";
        		}
        		else{
        			MsgBodyString2+="Your bid of<B> "+userBid+"$</B> is still the leading bid for this auction.<br><br>";
        		}
        		
        		MsgBodyString2+="please check out your Bidget bidding widget (or eBay) for recent changes."+"<br><br>";
        		MsgBodyString2+="Thank you,"+"<br>";
        		MsgBodyString2+="Bidget Team.";
        		
        		//if a picture was supplied for the product. put it in the mail:
        		if(!(productPicStr2.equals(null)) && !(productPicStr2.equals(""))){
        			MsgBodyString2+="<br><br><B>Product picture bellow:</B><br>";
        			String imgStr2 = "<img src='"+productPicStr2+"' align='middle'><br><br>"; 
        			MsgBodyString2+=imgStr2;
        			
        		}
        		        		
        		MsgBodyString2+="<table><tr></tr><td>____________________________________________________________</td><tr><td>"+BidGetLogoPicStr+"</td></tr><tr><td>";
        		MsgBodyString2+=ContactUsStr;
        		MsgBodyString2+="</td></tr></table>";
        		
        		emailSender.SendEmail(userName, 
        				"One of your auctions is about to end in "+timeToAlert+" minutes! - BidGet automatic notification", MsgBodyString2);
        		
        		//SMS sending to client:
        		if(!(CellNumStr.equals(null)) && !(CellNumStr.equals(""))){
            		String SmsContent;
            		if( userBid.equals("100000000")){
                		SmsContent="Auction "+timeID+" about to end in "+timeToAlert+" min. YOU'RE NOT LEADING!";
                		SmsSender.SendSMS(SmsContent, CellNumStr);
            		}
        		}

        	}
        }
    }
}
